package cn.sightsnow.zh.controller;

import cn.sightsnow.zh.entity.EasyDlResult;
import cn.sightsnow.zh.entity.Image;
import cn.sightsnow.zh.repository.EasyDlResultRepository;
import cn.sightsnow.zh.repository.ImageRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "分类结果查询")
@RestController
@RequestMapping("/api/classification")
@Slf4j
public class ClassificationController {

    @Autowired
    private EasyDlResultRepository easyDlResultRepository;

    @Autowired
    private ImageRepository imageRepository;

    @Value("${server.port:9080}")
    private String serverPort;

    @Value("${image.upload.path:images/upload/}")
    private String imageUploadPath;

    private String getBaseUrl(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        return scheme + "://" + serverName + ":" + serverPort;
    }

    @ApiOperation("获取准确率大于80%的分类结果")
    @GetMapping("/high-accuracy")
    public ResponseEntity<List<Map<String, Object>>> getHighAccuracyResults(HttpServletRequest request) {
        List<EasyDlResult> allResults = easyDlResultRepository.findAll();
        List<Map<String, Object>> highAccuracyResults = new ArrayList<>();
        String baseUrl = getBaseUrl(request);

        for (EasyDlResult result : allResults) {
            try {
                // 获取分类结果的准确率
                String resultName = result.getSort_result_name();
                if (resultName != null && resultName.endsWith("%")) {
                    // 提取分类名称（去除百分比部分）
                    String className = resultName.replaceAll("\\d+\\.?\\d*%", "").trim();
                    String percentStr = resultName.substring(0, resultName.length() - 1);
                    double accuracy = Double.parseDouble(percentStr) / 100;
                    
                    // 如果准确率大于80%
                    if (accuracy > 0.8) {
                        // 查找对应的图片
                        Image image = imageRepository.findByEasyDlResultId(result.getEasyDlResultId());
                        
                        Map<String, Object> resultMap = new HashMap<>();
                        resultMap.put("logId", result.getLog_id());
                        resultMap.put("classificationResult", className);
                        resultMap.put("recognitionTime", result.getRecognitionTime());
                        resultMap.put("accuracy", accuracy);
                        
                        if (image != null) {
                            resultMap.put("imageUrl", baseUrl + "/" + image.getImagePath());
                            resultMap.put("originalFilename", image.getOriginalFilename());
                        }
                        
                        highAccuracyResults.add(resultMap);
                    }
                }
            } catch (Exception e) {
                log.error("处理分类结果时出错: {}", e.getMessage());
            }
        }

        return ResponseEntity.ok(highAccuracyResults);
    }

    @ApiOperation("根据logId获取图片下载URL")
    @GetMapping("/image/{logId}")
    public ResponseEntity<?> getImageUrlByLogId(
            @ApiParam(value = "识别结果的logId", required = true)
            @PathVariable String logId,
            HttpServletRequest request) {
        try {
            // 根据logId.value查找图片
            Image image = imageRepository.findByLogIdValue(logId);
            
            if (image == null) {
                log.warn("未找到logId为{}的图片", logId);
                return ResponseEntity.notFound().build();
            }

            String baseUrl = getBaseUrl(request);
            Map<String, Object> response = new HashMap<>();
            response.put("imageUrl", baseUrl + "/" + image.getImagePath());
            response.put("originalFilename", image.getOriginalFilename());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取图片URL时出错: {}", e.getMessage());
            return ResponseEntity.internalServerError().body("获取图片URL时发生错误");
        }
    }

    @ApiOperation("直接获取图片文件")
    @GetMapping("/image/file/{filename}")
    public ResponseEntity<Resource> getImageFile(
            @ApiParam(value = "图片文件名", required = true)
            @PathVariable String filename) {
        try {
            // 去除文件名中的多余空格
            filename = filename.trim();
            
            // 构建图片完整路径
            String uploadDir = System.getProperty("user.dir") + File.separator + imageUploadPath;
            Path imagePath = Paths.get(uploadDir, filename);
            File file = imagePath.toFile();

            log.info("当前工作目录: {}", System.getProperty("user.dir"));
            log.info("图片上传路径配置: {}", imageUploadPath);
            log.info("处理后的文件名: {}", filename);
            log.info("完整的图片路径: {}", imagePath.toAbsolutePath());
            log.info("文件是否存在: {}", file.exists());
            
            if (!file.exists()) {
                log.warn("图片文件不存在: {}", imagePath);
                // 检查目录是否存在
                File directory = new File(uploadDir);
                log.info("上传目录是否存在: {}", directory.exists());
                if (directory.exists()) {
                    log.info("目录内容:");
                    File[] files = directory.listFiles();
                    if (files != null) {
                        for (File f : files) {
                            log.info("- {}", f.getName());
                        }
                    }
                }
                return ResponseEntity.notFound().build();
            }

            // 创建文件资源
            Resource resource = new FileSystemResource(file);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            headers.setContentDispositionFormData("attachment", filename);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            log.error("获取图片文件时出错: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @ApiOperation("根据logId直接获取图片文件")
    @GetMapping("/image/download/{logId}")
    public ResponseEntity<?> downloadImageByLogId(
            @ApiParam(value = "识别结果的logId", required = true)
            @PathVariable String logId) {
        try {
            // 根据logId查找图片
            Image image = imageRepository.findByLogIdValue(logId);
            
            if (image == null) {
                log.warn("未找到logId为{}的图片", logId);
                return ResponseEntity.notFound().build();
            }

            // 从图片路径中提取文件名
            String imagePath = image.getImagePath();
            String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
            
            log.info("找到图片文件: {}", fileName);
            
            // 构建图片完整路径
            String uploadDir = System.getProperty("user.dir") + File.separator + imageUploadPath;
            Path fullPath = Paths.get(uploadDir, fileName);
            File file = fullPath.toFile();

            if (!file.exists()) {
                log.warn("图片文件不存在: {}", fullPath);
                return ResponseEntity.notFound().build();
            }

            // 创建文件资源
            Resource resource = new FileSystemResource(file);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            headers.setContentDispositionFormData("attachment", fileName);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
            
        } catch (Exception e) {
            log.error("获取图片文件时出错: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body("获取图片文件时发生错误");
        }
    }
} 